package com.mai4j.practice.pdf;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import lombok.extern.slf4j.Slf4j;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.File;
import java.io.IOException;


/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Slf4j
public class ITextRendererHelper {

    private static ITextRenderer renderer;

    /**
     * 创建 ITextRenderer对象工厂
     *
     * @return ITextRenderer
     */
    public static synchronized ITextRenderer get() {
        if (renderer == null) {
            renderer = new ITextRenderer();
        }
        return renderer;
    }


    /**
     * 添加字体
     *
     * @param font font
     */
    public static void addFont(String font) throws PdfException {
        ITextFontResolver fontResolver = get().getFontResolver();
        try {
            fontResolver.addFont(font, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (DocumentException | IOException e) {
            throw new PdfException("添加字体" + font + "失败", e);
        }
    }

    /**
     * 添加目录下的字体
     *
     * @param fontPath 目录
     */
    public static void addFonts(String fontPath) {
        File fontsDir = new File(fontPath);
        if (fontsDir.isDirectory()) {
            File[] files = fontsDir.listFiles();
            if (files != null) {
                for (File f : files) {
                    if (f == null || f.isDirectory()) break;
                    try {
                        addFont(f.getAbsolutePath());
                    } catch (PdfException e) {
                        log.warn("添加字体" + f.getAbsolutePath() + "失败", e);
                    }
                }
            }
        }
    }
}
